package com.hexu.event.service;

import com.hexu.event.entity.Administrator;
import com.hexu.event.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

import static com.hexu.event.util.DaoUtil.administratorDao;
import static com.hexu.event.util.DaoUtil.userDao;

public class LoginService {

    //用户登录验证
    public boolean loginUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean result = false;
        //调用请求对象对请求体使用utf-8字符集进行重新编辑
        request.setCharacterEncoding("utf-8");
        //调用请求对象读取请求体参数信息
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        //调用Dao将查询验证信息推送到数据库服务器上
        result = userDao.loginUser(account,password);
        //调用响应对象，根据验证结果将不同资源文件地址写入到响应头，交给浏览器
        if(result){//用户存在
            System.out.println("用户登录成功");
        }
        return result;
    }

    //管理员登录验证
    public boolean loginAdministrator(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean result = false;
        //调用请求对象对请求体使用utf-8字符集进行重新编辑
        request.setCharacterEncoding("utf-8");
        //调用请求对象读取请求体参数信息
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        //调用Dao将查询验证信息推送到数据库服务器上
        result = administratorDao.loginAdministrator(account,password);
        //调用响应对象，根据验证结果将不同资源文件地址写入到响应头，交给浏览器
        if(result){//管理员存在
            System.out.println("管理员登录成功");
        }
        return result;
    }

    //登录验证
    public boolean login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean flagUser = loginUser(request,response);
        boolean flagAdministrator = loginAdministrator(request,response);
        //取出输入的账号
        String account = request.getParameter("account");
        //如果账号和密码输入正确
        if(flagUser){
            User user = userDao.getUser(account);
            //在判定来访用户身份合法后，通过请求对象向Tomcat申请为当前用户申请一个HttpSession
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            if(user.getServiceWork() == 0){
                response.sendRedirect("/hexu/UserIndex.html");
            }
            if(user.getServiceWork() == 1){
                response.sendRedirect("/hexu/WorkerIndex.html");
            }

            return  true;
        }else if(flagAdministrator){
            Administrator administrator = administratorDao.getAdministrator(account);
            //在判定来访用户身份合法后，通过请求对象向Tomcat申请为当前用户申请一个HttpSession
            HttpSession session = request.getSession();
            session.setAttribute("administrator",administrator);
            response.sendRedirect("/hexu/AdministratorIndex.html");
            return true;
        }
        return false;
    }

}
